/**
 * Created by joy on 25/09/2017.
 */
import BitcoinHelper from 'js-common-modules/lib/helpers/chain/BitcoinHelper'
import FileUtil from 'js-common-modules/lib/utils/FileUtil'
import bitcoin from 'bitcoinjs-lib'
import OsUtil from 'js-common-modules/lib/utils/OsUtil'

export default class Account {

  constructor () {
    this.accounts = []
    this._bitcoinHelper = new BitcoinHelper(bitcoin)
    this._mnemonic = this._loadMnemonic()
    const { seed, xpriv, xpub } = this._bitcoinHelper.getMasterPairByMnemonic(this._mnemonic)
    this._seed = seed
    this._masterPriv = xpriv
    this._masterPub = xpub
    this._basePath = 'm/0'
    this._baseXpub = this._bitcoinHelper.getXpubFromXpubByPath(this._masterPub, this._basePath)
    this._loadAccounts()
  }

  _loadMnemonic () {
    // 检查是否有过助记码
    const tempFile = global['dirs']['temp'] + '/temp.json'
    let obj = FileUtil.loadFromJsonFile(tempFile)
    if (obj && obj['mnemonic']) {
      return obj['mnemonic']
    }
    // 第一次启动，不存在助记码
    const mnemonic = this._bitcoinHelper.getRandomMnemonic() + ' ' + OsUtil.getUniqueSign()
    obj === null && (obj = {})
    obj['mnemonic'] = mnemonic
    FileUtil.writeSync(tempFile, JSON.stringify(obj))
    return mnemonic
  }

  _loadAccounts () {
    const accountsFile = global['dirs']['temp'] + '/accounts.json'
    const accounts = FileUtil.loadFromJsonFile(accountsFile)
    // logger.error(accountsFile, accounts)
    if (accounts && accounts.length > 0) {
      this.accounts = accounts
      logger.info('已从本地加载所有用户')
      logger.error('所有账户已加载: ', JSON.stringify(this.accounts))
    } else {
      // 没有任何账户，创建初始账户
      logger.info('没有任何账户，创建初始账户')
      this.getNewAccount(0, 'defaultAccount')
    }
  }

  getNewAccount (index, alias) {
    // 查重
    if (index < this.accounts.length) {
      return this.accounts[index]
    }
    const account = {
      path: `${this._basePath}/${index}`,
      address: this._bitcoinHelper.getAddressByXpubIndex(this._baseXpub, index),
      alias: alias
    }
    this.addAccount(account)
    return account
  }

  addAccount (account) {
    // {
    //   path: path,
    //   address: address,
    //   alias: alias
    // }
    this.accounts.push(account)
  }

}
